import React, { useState, useEffect } from 'react'
import { RefreshCw } from 'lucide-react'
import { toast } from 'react-hot-toast'
import { useKafkaStore } from '@/stores/kafkaStore'
import { kafkaApi } from '@/services/kafka'
import { useWebSocket } from '@/hooks/useWebSocket'

// 导入类型定义
import {
  MonitorOverview,
  TopicStats,
  MonitorHealthStatus,
  MonitorPerformanceMetrics,
  HistoricalData,
  HistoricalDataPoint,
  ChartData
} from '@/types/monitor'

// 导入拆分的组件
import SystemHealthCard from '@/components/Monitor/SystemHealthCard'
import OverviewCards from '@/components/Monitor/OverviewCards'
import PerformanceCharts from '@/components/Monitor/PerformanceCharts'
import TopicStatsTable from '@/components/Monitor/TopicStatsTable'
import PerformanceMetrics from '@/components/Monitor/PerformanceMetrics'
import ConsumerGroupMonitor from '@/components/Monitor/ConsumerGroupMonitor'
import ClusterHealthMonitor from '@/components/Monitor/ClusterHealthMonitor'

// 接口定义已移动到 @/types/monitor

export default function Monitor() {
  const [overview, setOverview] = useState<MonitorOverview | null>(null)
  const [topicStats, setTopicStats] = useState<TopicStats[]>([])
  const [healthStatus, setHealthStatus] = useState<MonitorHealthStatus | null>(null)
  const [performanceMetrics, setPerformanceMetrics] = useState<MonitorPerformanceMetrics | null>(null)
  const [historicalData, setHistoricalData] = useState<HistoricalData | null>(null)
  const [topicInfos, setTopicInfos] = useState<any[]>([]) // Topic管理接口的数据，包含真实分区数
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [lastUpdate, setLastUpdate] = useState<Date>(new Date())
  const [selectedTimeRange, setSelectedTimeRange] = useState<string>('1h')
  const [showCharts, setShowCharts] = useState(true)
  // 移除标签页状态，直接显示单页面

  // Kafka连接状态管理
  const { setConnectionStatus } = useKafkaStore()

  // WebSocket连接（为了状态一致性）
  const { connected } = useWebSocket()

  // 初始化连接状态和加载数据
  useEffect(() => {
    const initializeMonitor = async () => {
      try {
        // 首先检测Kafka连接状态
        const connectionResult = await kafkaApi.testConnection()
        if (connectionResult.success) {
          setConnectionStatus('已连接', true)
          // 连接成功后加载监控数据
          await loadAllData()
        } else {
          setConnectionStatus('连接失败', false)
          toast.error('Kafka连接失败，请检查配置')
        }
      } catch (error) {
        console.error('初始化监控面板失败:', error)
        setConnectionStatus('连接失败', false)
        toast.error('无法连接到Kafka服务器')
      } finally {
        setLoading(false)
      }
    }

    initializeMonitor()
  }, [setConnectionStatus])

  // WebSocket实时数据监听
  useEffect(() => {
    if (!connected) return

    // 订阅监控数据
    const subscribeToMonitor = () => {
      if (window.ws && window.ws.readyState === WebSocket.OPEN) {
        window.ws.send(JSON.stringify({
          type: 'subscribe_monitor'
        }))
      }
    }

    // 处理WebSocket消息
    const handleWebSocketMessage = (event: MessageEvent) => {
      try {
        const message = JSON.parse(event.data)
        console.log('收到WebSocket消息:', message.type)

        if (message.type === 'monitor_subscribed') {
          console.log('监控数据订阅成功:', message.message)
        } else if (message.type === 'monitor_update' && message.data) {
          console.log('收到实时监控数据更新:', message.data)

          // 更新监控数据
          if (message.data.overview) {
            setOverview(message.data.overview)
            console.log('更新概览数据')
          }
          if (message.data.topics) {
            setTopicStats(message.data.topics)
            console.log('更新Topic统计数据')
          }
          if (message.data.performance) {
            setPerformanceMetrics(message.data.performance)
            console.log('更新性能指标数据')

            // 当性能数据更新时，也更新历史数据（用于图表）
            loadHistoricalData(selectedTimeRange)
          }

          setLastUpdate(new Date())
          console.log('监控数据实时更新完成')
        }
      } catch (error) {
        console.error('处理WebSocket监控消息失败:', error)
      }
    }

    // 添加消息监听器
    if (window.ws) {
      window.ws.addEventListener('message', handleWebSocketMessage)
      subscribeToMonitor()
    }

    // 清理函数
    return () => {
      if (window.ws) {
        window.ws.removeEventListener('message', handleWebSocketMessage)
        // 取消订阅监控数据
        if (window.ws.readyState === WebSocket.OPEN) {
          window.ws.send(JSON.stringify({
            type: 'unsubscribe_monitor'
          }))
        }
      }
    }
  }, [connected])

  // 定时刷新数据（当WebSocket连接时禁用定时刷新，完全依赖实时更新）
  useEffect(() => {
    if (connected) {
      // WebSocket连接时不进行定时刷新，完全依赖实时更新
      return
    }

    // 只有在WebSocket未连接时才进行定时刷新
    const interval = setInterval(() => {
      if (!loading) {
        loadAllData(true) // 静默刷新
      }
    }, 30000) // 30秒刷新一次

    return () => clearInterval(interval)
  }, [loading, connected])

  // 加载所有监控数据
  const loadAllData = async (silent = false) => {
    try {
      if (!silent) {
        setRefreshing(true)
      }

      // 并行加载核心监控数据
      const [overviewRes, topicsRes, healthRes, performanceRes, historicalRes] = await Promise.allSettled([
        fetch('/api/monitor/overview').then(res => res.json()),
        fetch('/api/monitor/topics').then(res => res.json()),
        fetch('/api/monitor/health').then(res => res.json()),
        fetch('/api/monitor/performance').then(res => res.json()),
        fetch(`/api/monitor/historical?time_range=${selectedTimeRange}`).then(res => res.json())
      ])

      // 异步加载Topic信息，不阻塞主要数据显示
      loadTopicInfos()

      // 处理概览数据
      if (overviewRes.status === 'fulfilled') {
        setOverview(overviewRes.value)
      } else {
        console.error('加载概览数据失败:', overviewRes.reason)
      }

      // 处理Topic统计数据
      if (topicsRes.status === 'fulfilled') {
        setTopicStats(topicsRes.value)
      } else {
        console.error('加载Topic统计失败:', topicsRes.reason)
      }

      // 处理健康状态数据
      if (healthRes.status === 'fulfilled') {
        setHealthStatus(healthRes.value)
      } else {
        console.error('加载健康状态失败:', healthRes.reason)
      }

      // 处理性能指标数据
      if (performanceRes.status === 'fulfilled') {
        setPerformanceMetrics(performanceRes.value)
      } else {
        console.error('加载性能指标失败:', performanceRes.reason)
      }

      // 处理历史数据
      if (historicalRes.status === 'fulfilled') {
        setHistoricalData(historicalRes.value)
      } else {
        console.error('加载历史数据失败:', historicalRes.reason)
      }

      setLastUpdate(new Date())

      if (!silent) {
        toast.success('监控数据已更新')
      }

    } catch (error) {
      console.error('加载监控数据失败:', error)
      if (!silent) {
        toast.error('加载监控数据失败')
      }
    } finally {
      if (!silent) {
        setRefreshing(false)
      }
    }
  }

  // 加载历史数据
  const loadHistoricalData = async (timeRange: string) => {
    try {
      const response = await fetch(`/api/monitor/historical?time_range=${timeRange}`)
      const data = await response.json()
      setHistoricalData(data)
      setSelectedTimeRange(timeRange)
    } catch (error) {
      console.error('加载历史数据失败:', error)
      toast.error('加载历史数据失败')
    }
  }

  // 异步加载Topic信息（不阻塞主要数据）
  const loadTopicInfos = async () => {
    try {
      const response = await fetch('/api/topic-manager/topics')
      if (response.ok) {
        const topicInfosData = await response.json()
        setTopicInfos(topicInfosData)
        console.log('加载Topic信息成功:', topicInfosData.length, '个Topic')
      } else {
        console.error('加载Topic信息失败: HTTP', response.status)
      }
    } catch (error) {
      console.error('加载Topic信息失败:', error)
    }
  }

  // 手动刷新
  const handleRefresh = () => {
    loadAllData()
  }

  // 格式化数字
  const formatNumber = (num: number) => {
    if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + 'M'
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'K'
    }
    return num.toString()
  }

  // 计算真实的总分区数
  const getTotalPartitions = () => {
    return topicInfos.reduce((total, topic) => total + (topic.partitions || 0), 0)
  }

  // 创建包含真实分区数的概览数据
  const getEnhancedOverview = () => {
    if (!overview) return null
    return {
      ...overview,
      total_partitions: getTotalPartitions()
    }
  }

  // 格式化字节
  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 准备图表数据
  const prepareChartData = () => {
    if (!historicalData || historicalData.dataPoints.length === 0) {
      return null
    }

    const dataPoints = historicalData.dataPoints
    const labels = dataPoints.map(point => {
      const date = new Date(point.timestamp)
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    })

    // CPU、内存、磁盘使用率图表数据
    const systemUsageData = {
      labels,
      datasets: [
        {
          label: 'CPU使用率',
          data: dataPoints.map(point => point.cpu_usage),
          borderColor: '#3b82f6',
          backgroundColor: 'rgba(59, 130, 246, 0.1)',
          fill: true,
          tension: 0.4
        },
        {
          label: '内存使用率',
          data: dataPoints.map(point => point.memory_usage),
          borderColor: '#10b981',
          backgroundColor: 'rgba(16, 185, 129, 0.1)',
          fill: true,
          tension: 0.4
        },
        {
          label: '磁盘使用率',
          data: dataPoints.map(point => point.disk_usage),
          borderColor: '#f59e0b',
          backgroundColor: 'rgba(245, 158, 11, 0.1)',
          fill: true,
          tension: 0.4
        }
      ]
    }

    // Kafka指标图表数据（生产和消费两条线）
    const kafkaMetricsData = {
      labels,
      datasets: [
        {
          label: '消息生产速率',
          data: dataPoints.map(point => point.kafka_messages_per_second || 0),
          borderColor: '#10b981',
          backgroundColor: 'rgba(16, 185, 129, 0.1)',
          fill: false,
          tension: 0.4
        },
        {
          label: '消息消费速率',
          data: dataPoints.map(point => 0), // 目前没有消费速率数据，显示为0
          borderColor: '#f59e0b',
          backgroundColor: 'rgba(245, 158, 11, 0.1)',
          fill: false,
          tension: 0.4
        }
      ]
    }

    // Topic分区数量柱状图数据 - 使用真实分区数
    const getTopicPartitions = (topicName: string): number => {
      const topicInfo = topicInfos.find(info => info.name === topicName)
      return topicInfo?.partitions || 1
    }

    const topicPartitionsData = {
      labels: topicStats.map(topic => topic.name),
      datasets: [
        {
          label: '分区数量',
          data: topicStats.map(topic => getTopicPartitions(topic.name)),
          backgroundColor: [
            '#3b82f6',
            '#10b981',
            '#f59e0b',
            '#ef4444',
            '#8b5cf6',
            '#06b6d4'
          ],
          borderColor: [
            '#2563eb',
            '#059669',
            '#d97706',
            '#dc2626',
            '#7c3aed',
            '#0891b2'
          ],
          borderWidth: 1
        }
      ]
    }

    return {
      systemUsage: systemUsageData,
      kafkaMetrics: kafkaMetricsData,
      topicPartitions: topicPartitionsData
    }
  }

  const chartData = prepareChartData()

  if (loading) {
    return (
      <div className="space-y-8">
        <div className="text-center py-16">
          <div className="inline-block animate-spin rounded-full h-16 w-16 border-4 border-primary-200 border-t-primary-600"></div>
          <p className="mt-6 text-lg text-gray-600 font-medium">加载监控数据...</p>
          <p className="mt-2 text-sm text-gray-500">正在获取Kafka集群状态</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-8">
      {/* 页面标题和刷新按钮 */}
      <div className="flex flex-col lg:flex-row lg:justify-between lg:items-center space-y-4 lg:space-y-0">
        <div className="text-center lg:text-left">
          <h1 className="text-3xl font-bold gradient-text mb-2">监控面板</h1>
          <p className="text-lg text-gray-600">Kafka集群实时监控和性能指标</p>
        </div>
        <div className="flex flex-col sm:flex-row items-center space-y-2 sm:space-y-0 sm:space-x-4">
          <div className="flex items-center space-x-3 px-4 py-2 bg-gray-50 rounded-lg">
            <span className="text-sm text-gray-600 font-medium">
              最后更新: {lastUpdate.toLocaleTimeString()}
            </span>
            {connected && (
              <div className="flex items-center space-x-2">
                <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
                <span className="text-xs text-green-600 font-semibold">实时连接</span>
              </div>
            )}
          </div>
          <button
            onClick={handleRefresh}
            disabled={refreshing}
            className="btn-outline hover-lift"
            title="手动刷新监控数据"
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${refreshing ? 'animate-spin' : ''}`} />
            刷新数据
          </button>
        </div>
      </div>

      {/* 系统监控概览 */}

      {/* 系统健康状态卡片 */}
      <SystemHealthCard healthStatus={healthStatus} />

      {/* 概览统计卡片 */}
      <OverviewCards overview={getEnhancedOverview()} performanceMetrics={performanceMetrics} />

      {/* 图表展示区域 */}
      <PerformanceCharts
        showCharts={showCharts}
        chartData={chartData}
        selectedTimeRange={selectedTimeRange}
        onTimeRangeChange={loadHistoricalData}
        performanceMetrics={performanceMetrics}
        topicStats={topicStats}
      />

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Topic统计表格 */}
        <TopicStatsTable
          topicStats={topicStats}
          formatNumber={formatNumber}
          topicRates={{}} // 暂时传递空对象，后续可以从performanceMetrics中提取
          topicInfos={topicInfos} // 传递真实分区数据
        />

        {/* 性能指标 */}
        <PerformanceMetrics performanceMetrics={performanceMetrics} formatBytes={formatBytes} />
      </div>

      {/* 消费者组监控 */}
      <div className="mt-6">
        <ConsumerGroupMonitor />
      </div>

      {/* 集群健康监控 */}
      <div className="mt-6">
        <ClusterHealthMonitor />
      </div>
    </div>
  )
}
